package com.exercises;

import com.alibaba.fastjson.JSONObject;
import com.exercises.common.TreeNode;

import java.util.*;
import java.util.stream.Collectors;

class Exercise629 {
    public static void main(String[] args) {
        topKFrequent(new String[]{"i", "love", "leetcode", "i", "love", "coding"}, 7);
    }

    public static List<String> topKFrequent(String[] words, int k) {
        TreeMap<String, Integer> treeMap = new TreeMap<>();

        for (String key : words) {
            treeMap.put(key, treeMap.getOrDefault(key, 0) + 1);

        }

//        List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(treeMap.entrySet());
//
//        Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
//            @Override
//            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
//                return o2.getValue() - o1.getValue() == 0 ? o2.getValue() - o1.getValue() : o1.getKey().compareTo(o2.toString());
//                PriorityQueue}
//        });
//
//        return list.subList(0, k).stream().map(e -> e.getKey()).collect(Collectors.toList());


        PriorityQueue<Map.Entry<String, Integer>> queue = new PriorityQueue<>(new Comparator<Map.Entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                return o2.getValue() - o1.getValue() != 0 ? o1.getValue().compareTo(o2.getValue()) : o2.getKey().compareTo(o1.toString());
            }
        });

        for (Map.Entry<String, Integer> entry : treeMap.entrySet()) {
            queue.offer(entry);
            if (queue.size() > k) {
                queue.poll();
            }
        }
        List<String> result = new ArrayList<>();
        while (!queue.isEmpty()) {
            result.add(queue.poll().getKey());
        }
        Collections.reverse(result);
        return result;
    }
}
